package com.pig4cloud.pig.demo.Service.impl;

import com.alibaba.fastjson.JSON;
import com.pig4cloud.pig.demo.feign.Entity.ArticleBriefs;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class ArticleBriefsService {

    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient client;

    @Value("${article.index}")
    private String esIndex;

    public ArticleBriefs findArticleBriefs() throws Exception{
        GetRequest getRequest = new GetRequest("testaa", "1");
        GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
        System.out.println(getResponse.getSourceAsString());
        //将索引中的数据取出,封装到实体类
        ArticleBriefs articleBriefs=new ArticleBriefs();
        articleBriefs.setAuthor((String)getResponse.getSource().get("author"));
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
        Date time=format1.parse((String)getResponse.getSource().get("issueTime"));
        articleBriefs.setIssueTime(time);
        articleBriefs.setTitle((String)getResponse.getSource().get("title"));
        articleBriefs.setCommentNum((int)getResponse.getSource().get("commentNum"));
        articleBriefs.setGlanceNum((int)getResponse.getSource().get("glanceNum"));
        articleBriefs.setCollectNum((int)getResponse.getSource().get("collectNum"));
        articleBriefs.setImg((String)getResponse.getSource().get("img"));
        System.out.println(articleBriefs);

        return articleBriefs;
    }

    public List<ArticleBriefs> findAllArticleBriefs() throws ParseException, IOException {
        //构建请求
        SearchRequest searchRequest = new SearchRequest(esIndex);

        //构建搜索条件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.highlighter();
        // 查询条件，我们可以使用 QueryBuilders 工具来实现        
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("class","java");
//        TermQueryBuilder termQueryBuilder2 = QueryBuilders.termQuery("class","a");
//        TermQueryBuilder termQueryBuilder3 = QueryBuilders.termQuery("class","v");
//        TermQueryBuilder termQueryBuilder4 = QueryBuilders.termQuery("class","a");
        sourceBuilder.query(termQueryBuilder);
//        sourceBuilder.query(termQueryBuilder2);
//        sourceBuilder.query(termQueryBuilder3);
//        sourceBuilder.query(termQueryBuilder4);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        //将搜索条件加入到请求体中
        searchRequest.source(sourceBuilder);

        //发送请求  获取响应
        SearchResponse searchResponse = client.search(searchRequest,RequestOptions.DEFAULT);
        //构建一个用来存储实体类的列表
        List<ArticleBriefs> list = new ArrayList<>();
        for (SearchHit documentFields : searchResponse.getHits().getHits()) {
            //构造对象
            ArticleBriefs articleBriefs=new ArticleBriefs();
            documentFields.getSourceAsMap().get("title");
            articleBriefs.setAuthor((String)documentFields.getSourceAsMap().get("author"));
            SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
            Date time=format1.parse((String)documentFields.getSourceAsMap().get("issueTime"));
            articleBriefs.setIssueTime(time);
            articleBriefs.setTitle((String)documentFields.getSourceAsMap().get("title"));
            articleBriefs.setCommentNum((int)documentFields.getSourceAsMap().get("commentNum"));
            articleBriefs.setGlanceNum((int)documentFields.getSourceAsMap().get("glanceNum"));
            articleBriefs.setCollectNum((int)documentFields.getSourceAsMap().get("collectNum"));
            articleBriefs.setImg((String)documentFields.getSourceAsMap().get("img"));
            list.add(articleBriefs);
            System.out.println("=+++++++++++++++++++++++++++++++++++++++++++++++++++++++");
        }
        System.out.println(list);
        return list;
    }

    //根据前端传来的类别,搜索对应的热门文章
    public Map<String,List<ArticleBriefs>> findAllByClass(List<String> list,int price) throws IOException, ParseException {
        //创建存放类别List的map
        Map<String,List<ArticleBriefs>> map = new HashMap<>();
        //通过循环将类list存入map
        for(String s:list){
            System.out.println(s+":开始");
            //搜索需要将英文转换为小写,不然搜不到
            String s2=s.toLowerCase();
            //构建请求
            SearchRequest searchRequest = new SearchRequest();
            //多个精准查询
            BoolQueryBuilder must = QueryBuilders.boolQuery();

            //构建搜索条件
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            sourceBuilder.highlighter();
            //如果是热门文章就根据浏览次数搜索,如果不是就根据类型和浏览次数搜索
            if(!"热门文章".equals(s2)){
//                如果有非字母的字符串就以非字母字符串为截点,将字符串分割成多个子字符串,再分别放入搜索条件
                String cut="[^a-z]";
                String[] split = s2.split(cut);
                for(String ss:split) {
                    TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("class",ss);
                    must.must(termQueryBuilder);
                }
                sourceBuilder.query(must);
            }
            //如果price是0,代表免费,不为0代表收费
            if(price==0){
                TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("price",0);
                must.must(termQueryBuilder);
            }else{
                TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("price",0);
                must.mustNot(termQueryBuilder);
            }
            //搜索排好序的前六个
            sourceBuilder.sort(new FieldSortBuilder("viewnum").order(SortOrder.DESC));
            sourceBuilder.from(0);
            sourceBuilder.size(6);
            sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

            //将搜索条件加入到请求体中
            searchRequest.source(sourceBuilder);

            //发送请求  获取响应
            SearchResponse searchResponse = client.search(searchRequest,RequestOptions.DEFAULT);
            //构建一个用来存储实体类的列表
            List<ArticleBriefs> listA = new ArrayList<>();
            //将属性值封装到实体类对象里
            for (SearchHit documentFields : searchResponse.getHits().getHits()) {

                //构造对象
                ArticleBriefs articleBriefs=new ArticleBriefs();
                //设置实体类对象的属性
                articleBriefs.setAuthor((String)documentFields.getSourceAsMap().get("person"));
                SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
                Date time=format1.parse((String)documentFields.getSourceAsMap().get("publish_time"));
                articleBriefs.setIssueTime(time);
                articleBriefs.setTitle((String)documentFields.getSourceAsMap().get("title"));
//                articleBriefs.setCommentNum((int)documentFields.getSourceAsMap().get("commentNum"));
//                articleBriefs.setGlanceNum((int)documentFields.getSourceAsMap().get("viewnum"));
//                articleBriefs.setCollectNum((int)documentFields.getSourceAsMap().get("collectNum"));
                articleBriefs.setImg((String)documentFields.getSourceAsMap().get("pic_url"));
//                articleBriefs.setClasses((String)documentFields.getSourceAsMap().get("class"));
                articleBriefs.setPrice((double)documentFields.getSourceAsMap().get("price"));
                System.out.println(articleBriefs);
                //将实体类放入列表中
                listA.add(articleBriefs);
                System.out.println("=+++++++++++++++++++++++++++++++++++++++++++++++++++++++");
            }
            map.put(s,listA);
            System.out.println(s+":结束");

        }
        System.out.println("----------------------------------------------------------------------");
        System.out.println("map的值:"+map);
        return map;
    }
}
